<template>
    <div class="ui container main">
        <div class="ui container">
            <el-select size="mini" v-model="timeValue">
                <el-option
                    v-for="(i1,i0) in timeType.name.length"
                    :key="i0"
                    :label="timeType.name[i0]"
                    :value="timeType.value[i0]">
                </el-option>
            </el-select>
            <span style="margin-left: 60px" v-if="timeValue == 'time'">
                <el-date-picker size="mini" placeholder="选择开始日期" value-format="yyyy-MM-dd" v-model="time.start" ></el-date-picker>
                &nbsp;至&nbsp;
                <el-date-picker size="mini" placeholder="选择结束日期" value-format="yyyy-MM-dd" v-model="time.end" ></el-date-picker>
            </span>
            <div class="ui mini blue button" @click="getActivities(pagination.currentPage, pagination.pageSize, time.start, time.end )">查询</div> 
            <div class="ui right floated mini positive button" @click="showModal" ><i class="el-icon-plus"></i>创建活动</div> 
        </div>
        <div class="ui section hidden divider"></div>
        <el-table :data="tableData" v-loading="tableLoading" >
            <el-table-column label="时间">
                <template slot-scope="scope">
                    <div>{{moment(scope.row.timeStart).format('YYYY-MM-DD HH:mm:ss')}} 至</div>
                    <div>{{moment(scope.row.timeEnd).format('YYYY-MM-DD HH:mm:ss')}}</div>
                </template>
            </el-table-column>
            <el-table-column label="地点" prop="location"></el-table-column>
            <el-table-column label="事件" prop="event.label"></el-table-column>
            <el-table-column label="匹配度" prop="event.label"></el-table-column>
            <el-table-column label="操作" prop="status" width="100">
                <template slot-scope="scope">   
                    <div class="ui mini button" :class="scope.row.status == 'private' ? 'blue' : 'positive'" @click="changeEventStatus(scope.row)">{{scope.row.status == 'private' ? '公开' : '关闭'}}</div>
                </template>
            </el-table-column>
        </el-table>
        <el-row type="flex" justify="center">
            <el-pagination
                @current-change="getActivities(pagination.currentPage, pagination.pageSize, time.start, time.end )"
                :current-page.sync="pagination.currentPage"
                :page-size="pagination.pageSize"
                layout="total, prev, pager, next"
                :total="pagination.total">
            </el-pagination>
        </el-row>
        <div class="ui large modal">
            <div class="header">编辑你的一个事件</div>
            <div class="content">
                <form class="ui form edit">
                    <div class="field">
                        <div class="ui fluid top attached tablet stackable steps">
                            <div :class="(stepData.isActive[i] ? 'active' : '') + ' step'" v-for="(willNotUse, i) in 3" :key="i">
                                <i :class="stepData.icon.class[i] + ' icon'"></i>
                                <div class="content">
                                    <div class="title">{{stepData.icon.name[i]}}</div>
                                    <div class="description" style="font-size: 10px">
                                        {{handleDesc(i)}}
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="ui attached segment">
                            <div class="ui two column grid" v-if="currentTabIndex == 0">
                                <div class="column">
                                    <div class="ui left aligned container content-vertical-aligined">                
                                        <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" class="protected" v-model="eventTime.start" size="mini" type="datetime" placeholder="请选择起始时间"></el-date-picker>                                        
                                        &nbsp;&nbsp;--至--&nbsp;&nbsp;
                                        <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" class="protected" v-model="eventTime.end" size="mini" type="datetime" placeholder="请选择结束时间"></el-date-picker>                        
                                    </div>
                                </div>
                                <div class="column">
                                    <div v-if="eventTime.start">
                                        <h4 class="ui dividing header">起始时间</h4>
                                        {{eventTime.start}}
                                    </div>
                                    <div class="ui hidden divider"></div>
                                    <div v-if="eventTime.end">
                                        <h4 class="ui dividing header">结束时间</h4>
                                        {{eventTime.end}}
                                    </div>
                                </div>
                            </div>
                            <div class="ui two column grid" v-if="currentTabIndex == 1">
                                <div class="column">
                                    <div class="ui left aligned container">
                                        <div class="ui raised grey inverted segment map-container">
                                            <!-- 腾讯地图API start -->
                                            <iframe id="mapPage" width="100%" height="100%" frameborder=0
                                                src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&referer=myapp">
                                            </iframe>
                                                <!-- 腾讯地图API end -->
                                            </div>
                                        </div>
                                    </div>
                                <div class="column">
                                    <div class="ui container" v-if="map_location.name">
                                        <h4 class="ui dividing header">您选择的地址</h4>
                                        {{map_location.name}}
                                        <h4 class="ui dividing header">经纬度</h4>
                                        {{`X: ${map_location.x} &nbsp;&nbsp;Y: ${map_location.y}`}}
                                    </div>
                                </div>
                            </div>
                            <div class="ui left aligined container" v-if="currentTabIndex == 2">
                                <div data-tooltip="该功能尚未开放" data-position="left center">
                                    <div class="ui disabled search">
                                        <div class="ui transparent left icon input">
                                            <input type="text" placeholder="搜索活动..." class="prompt" v-model="keyword" @keyup="getActivityDebounced">
                                            <i class="search icon"></i>
                                        </div>
                                        <div class="results"></div>
                                    </div>
                                </div>
                                
                                <div class="ui hidden divider"></div>
                                <div class="ui basic segment">
                                    <h4 class="ui header">热门活动</h4>
                                    <div class="ui hidden divider"></div>
                                    <div class="ui center aligned grid">
                                        <div class="five column row">
                                            <div class="column" v-for="(item, i0) in iconData" :key="i0">
                                                <div :class="'ui special ' + (item.active ? 'red' : '') + ' link card'" @click="iconData.map(_ => {_.active = false});item.active = true;activeEvent = item">
                                                    <div class="content">
                                                        <icon :name="item.icon" scale="10"></icon>
                                                        <div class="center">{{ item.label }}</div>
                                                    </div>  
                                                </div>
                                            </div>                                
                                        </div>
                                    </div>
                                    <h4 class="ui dividing header" v-if="activeEvent.label">你选择的事件</h4>
                                    {{activeEvent.label}}
                                </div>
                            </div>
                        </div>
                    </div>
                </form>    
            </div>
            <div class="actions">
                <div class="ui blue button" v-if="currentTabIndex == 1 || currentTabIndex == 2" @click="changeStep('prev')">上一步</div>
                <div class="ui blue button" :class="{'disabled': !showUpCondition, 'ok': currentTabIndex == 2 }" 
                @click="currentTabIndex == 2 ? createEvent(eventTime.start, eventTime.end, map_location.x, map_location.y,map_location.name, activeEvent.eid) : changeStep('next')">
                    {{currentTabIndex == 2 ? '完成' : '下一步'}}
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import { api_event, api_activity } from '@/api'
export default {
    data () {
        return {
            tableData: [],
            tableLoading: false,
            pagination: {
                total: 20,
                pageSize: 20,
                currentPage: 1
            },
            time: {
                start: '',
                end: ''
            },
            timeType: {
                name: ['未来一周', '未来一个月', '确切日期'],
                value: ['week', 'month', 'time']
            },
            timeValue: 'week',
            // modal content data start ==========================================================
            stepData: {
                icon: {
                    class: ['time', 'building', 'coffee'],
                    name: ['Time', 'Place', 'Activity']
                },
                desc: ['发生的时间段', '发生的地点', '的类型'],
                isActive: [true, false, false]
            },
            currentTabIndex: 0,
            eventTime: {
                start: '',
                end: ''
            },
            activeEvent: {},
            keyword: '',
            map_location: {
                name: '',
                x: 0,
                y: 0
            },
            iconData: [],
            clicked: [true, false]
            // modal content data end ==========================================================
        }
    },
    mounted () {
        this.handleTime(this.timeValue)
        // modal content init start ==========================================================
        let self = this
        // tencent api
        window.addEventListener('message', (event) => {
            var loc = event.data
            if (loc && loc.module === 'locationPicker') {
                self.map_location.name = loc.poiaddress
                self.map_location.x = loc.latlng.lat
                self.map_location.y = loc.latlng.lng
            }
        }, false)
        // dimmer card
        // console.log($('.map-container'));

        $('.special.card').dimmer({
            on: 'hover'
        })

        $('.ui.search').search({
            source: this.content
        })
        this.getHotEvent()
        this.getActivities(1, this.pagination.pageSize, this.time.start, this.time.end)
        // modal content init end ==========================================================
    },
    methods: {
        getActivities (currentPage, pageSize, timeStart, timeEnd) {
            this.$http({
                method: 'get',
                url: api_activity + '/list',
                params: {
                    current_page: currentPage,
                    page_size: pageSize,
                    time_start: timeStart,
                    time_end: timeEnd
                }
            }).then(res => {
                this.tableData = res.data.reverse()
            })
        },
        changeEventStatus (activity) {
            let message = '关闭后，该活动仅对自己可见',
                targetStatus = 'private'

            if (activity.status === 'private') {
                message = '公开后，他人能够通过活动匹配发现你'
                targetStatus = 'public'
            }

            this.$confirm(message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
            .then(() => {
                this.$http({
                    url: `${api_activity}/create`,
                    method: 'put',
                    data: {
                        status: targetStatus,
                        eid: activity.eid
                    }
                })
                .then(() => {
                    activity.status = targetStatus
                    this.$message({
                        type: 'success',
                        message: '操作成功!'
                    })
                })
            })
        },
        handleTime (val) {
            // let today = new Date(_.now())
            this.time.start = this.moment().format('YYYY-MM-DD')
            let day = 7
            switch (val) {
            case 'week':
                day = 7
                break
            case 'month':
                day = 30
                break
            default:
                return false
            }
            this.time.end = this.moment().add(day, 'days').format('YYYY-MM-DD')
        },
        showModal () {
            $('.ui.modal').modal('show')
        },
        // modal content methods start ==========================================================
        async getActivity () {
            let res = await this.$http({
                url: api_event,
                method: 'get',
                params: {
                    keyword: this.keyword
                }
            })
            .then(res => res)
            .catch(e => console.log(e))
        },
        changeStep (flag) {
            flag === 'next' ? this.currentTabIndex++ : this.currentTabIndex--
            this.stepData.isActive.fill(false)
            this.$set(this.stepData.isActive, this.currentTabIndex, true)
        },
        getHotEvent () {
            this.$http({
                url: api_event + '/hot',
                method: 'get'
            })
            .then(res => {
                this.iconData = res.data
            })
            .catch(e => console.log(e, 'get hot event'))
        },

        createEvent (timeStart, timeEnd, locationX, locationY, location, eid) {
            this.$http({
                method: 'post',
                url: `${api_activity}/create`,
                data: {
                    timeStart: timeStart,
                    timeEnd: timeEnd,
                    locationX: locationX,
                    locationY: locationY,
                    location: location,
                    eid: eid
                }
            })
            .then(res => {
                this.getActivities(1, this.pagination.pageSize, this.time.start, this.time.end)
            })
        },
        handleDesc (i) {
            let [time, mapL] = [this.time, this.map_location]
            if (i === 0 && time.start && time.end) {
                return `${time.start} -- ${time.end}`
            }
            if (i === 1 && mapL.name) {
                return mapL.name
            }
            if (i === 2 && this.activeEvent.label) {
                return this.activeEvent.label
            }
            return '选择事件' + this.stepData.desc[i]
        }
        // modal content methods end ==========================================================
    },
    watch: {
        'timeValue': function (val) { this.handleTime(val) }
    },
    computed: {
        showUpCondition: function () {
            let time = this.eventTime
            return (this.stepData.isActive[0] && time.start && time.end && time.start < time.end) ||
            (this.stepData.isActive[1] && this.map_location.name) ||
            this.activeEvent.label
        }
    },
    created () {
        this.getActivityDebounced = _.debounce(this.getActivity, 2000)
    }
}
</script>

<style scoped lang="stylus">
.content-vertical-aligined
    display: flex
    align-items center

.map-container
    width 400px
    height 480px
    border-radius 10px
    padding 6px
</style>
